require "rake/clean" 
require "fileutils"

suffix_dir = "src/eventfax/core"
base_dir = File.dirname(__FILE__)
source_dir = File.expand_path(File.dirname(__FILE__) + "/src/eventfax/core")
target_dir = File.expand_path(File.dirname(__FILE__) + "/output")
example = File.expand_path(File.dirname(__FILE__) + "/examples")
bin_dir = File.expand_path(File.dirname(__FILE__) + "/bin")
jar_file = "output/eventfax.jar"

desc "Compile class files"
task :compile do
  source_files = Dir["#{source_dir}/**/*.scala"]
  source_files += Dir["src/eventfax/protocol/**/*.scala"]
  unless source_files.empty?
    compile_str = source_files.join(" ")
    system("fsc #{compile_str} -d #{target_dir}")
  end
end

desc "Compile Example files"
task :bin do
  source_files = Dir["#{example}/**/*.scala"]
  unless source_files.empty?
    compile_str = source_files.join(" ")
    system("fsc -cp #{target_dir}:. #{compile_str} -d #{bin_dir}")
  end
end

desc "Compile line protocol tester"
task :protocol do
  source_files = Dir["#{example}/**/test_line_protocol.scala"]
  unless source_files.empty?
    compile_str = source_files.join(" ")
    system("fsc -cp #{target_dir}:. #{compile_str} -d #{bin_dir}")
  end
end

desc "Create Jar file"
task :jar do
  sh "cd output; jar cf eventfax.jar eventfax/"
end

desc "Compile One or All specs"
task :spec => [:compile] do
  if ENV['SPEC']
    # compile and run one particular spec
  else
    spec_files = Dir["tests/**/*.scala"]
    unless spec_files.empty?
      compile_str = spec_files.join(" ")
      sh("fsc -cp #{target_dir}:lib/specs-1.1.4.jar:. #{compile_str} -d spec_out")
    end
  end
end

desc "compile and run one or all specs"
task :test => [:spec] do 
  if ENV['SPEC']
    class_name = ENV['SPEC']
    sh("cd spec_out; scala -cp #{target_dir}:#{base_dir}/lib/specs-1.1.4.jar:. #{class_name}")
  else 
    spec_runners = Dir["spec_out/**/*.class"]
    spec_runners.each do |runner|
      next if(runner !~ /Runner/)
      next if runner =~ /.*\$\.class$/
      class_name = $1 if runner =~ /\/(.+)\./
      system("cd spec_out; scala -cp #{target_dir}:#{base_dir}/lib/specs-1.1.4.jar:. #{class_name}")
    end
  end
end


task :clean do
  FileUtils.rm_r Dir.glob("#{target_dir}/*.class")
  FileUtils.rm_r Dir.glob("#{target_dir}/eventfax/core/*.class")
end

task :clobber do
  FileUtils.rm_r Dir.glob("#{bin_dir}/*.class")
end
